// shopMallPackage/pages/exchangeActivity/exchangeActivity.js
import { queryStoreDetail, getAddressDefault, getMyWallet, getReceiveAddressDetail, shopBuyRequest, mallBuyRequest, activitySignUpRequest } from "../../../service/onetoone_service"
const app = getApp();
import mathUtil from "../../../tools/mathUtils/mathUtil"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    formData: {
      activityId: null,
      payType: 2,
      bookingTime: "",
      contactName: "",
      contactPhone: "",
      remark: "",
      travelInfo: []
    },
    maxDate: new Date(2030, 11, 31).getTime(),
    minDate: new Date().getTime(),
    showLiveTimePop: false,
    // travelInfo对象里面是姓名和身份证号
    travelInfo: [{
      name: "",
      idCard: "",
    }],
    detailId: null,
    mealId: null,
    activityDetail: {},//活动详情
    mealData: {},//套餐内容
    payType: 2,// 1: 积分支付 2:微信支付
    houseDetail: {},
    addressData: { realName: "" },//默认地址
    balanceMoney: 0,
    addressId: null,// 选中的收货地址id
    isShowScorePay: true,
    showTextTitle: "确认支付",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // if (options.id) {

    //   // this.setData({
    //   //   mealData: app.globalData.mealData,
    //   //   mealId: options.mealId,
    //   //   'formData.productItemId': options.mealId,
    //   //   'formData.productId': options.id
    //   // })
    //   // this.queryStoreDetail();
    //   // this.getAddressDefault();
    //   // this.myWalletInfo();
    //   // setTimeout(() => {
    //   //   this.selectPayType();
    //   // }, 1500)
    // }
    this.setData({
      activityDetail: app.globalData.activityDetail,
      showTextTitle: "确认支付x" + app.globalData.activityDetail.integral + "元"
    })

    setTimeout(() => {
      this.setData({
        'formData.activityId': this.data.activityDetail.id
      })

    }, 300)
  },

  selectPayType() {
    if (this.data.balanceMoney < (this.data.mealData.price + this.data.houseDetail.postage)) {
      this.setData({
        isShowScorePay: false,
        "formData.payType": 2,
        payType: 2,
      })
    }
  },
  onChangePrice(e) {
    // console.log("JJLog:加减操作:" + JSON.stringify(e));
    let num = e.detail;
    if (this.data.balanceMoney < (this.data.mealData.price * num + this.data.houseDetail.postage)) {
      this.setData({
        isShowScorePay: false,
        "formData.payType": 2,
        payType: 2,
      })
    } else {
      this.setData({
        isShowScorePay: true,
        "formData.payType": 1,
        payType: 1,
      })
    }
    this.setData({
      'formData.buyNum': num
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.selectAddressId) {
      this.setData({
        addressId: app.globalData.selectAddressId
      })
      app.globalData.selectAddressId = null;
      this.getReceiveAddressDetail();
    }
  },
  getReceiveAddressDetail() {
    wx.showLoading();
    getReceiveAddressDetail(this.data.addressId).then(res => {
      console.log("JJLog:收货地址详情===:" + JSON.stringify(res));
      wx.hideLoading();
      if (res.code == 200) {
        this.setData({
          addressData: res.data,
          'formData.addressId': res.data.id,
        })
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || "查询失败",
        icon: "none"
      })
      console.error("JJLog:getReceiveAddressDetail", err);
    })
  },

  //获取我的积分数据:
  myWalletInfo() {
    getMyWallet().then(res => {
      console.log("JJLog:钱包数据===:" + JSON.stringify(res));
      if (res.code == 200) {
        this.setData({
          balanceMoney: res.data.restMoney || 0,
        })
      }
    }).catch(err => {
      console.error("JJLog:getMyWallet", err);
    })
  },
  payTypeChange(e) {
    let index = e.currentTarget.dataset.index;
    if (!this.data.isShowScorePay && index == 1) {
      wx.showToast({
        title: '您的积分不足以购买此商品',
        icon: "none"
      })
      return;
    }
    this.setData({
      payType: index,
      'formData.payType': index,
    })
  },
  //查询商品详情:
  queryStoreDetail() {
    wx.showLoading({
      title: '加载中...',
    })
    queryStoreDetail(this.data.detailId).then(res => {
      wx.hideLoading();
      console.log("JJLog:商品详情是:" + JSON.stringify(res));
      if (res.code == 200) {
        this.setData({
          houseDetail: res.data
        })
        // this.dealMealMoneyShow(res.data);
      }
    }).catch(err => {

      console.error("JJLog:queryStoreDetail:", err);
      wx.hideLoading();
      wx.showToast({
        title: err || "详情获取失败",
        icon: "none"
      })
      setTimeout(() => {
        wx.navigateBack({
          delta: 0,
        })
      }, 2000);
    })
  },
  dealMealMoneyShow(data) {
    // let items = data.items;

  },
  getAddressDefault() {
    getAddressDefault().then(res => {
      console.log("JJLog:默认地址是:" + JSON.stringify(res));
      if (res.code == 200) {
        this.setData({
          addressData: res.data,
        })
        if (this.data.addressData.id) {
          this.setData({
            'formData.addressId': this.data.addressData.id,
          })
        }
      }
    }).catch(err => {
      console.error("JJLog:getAddressDefault:", err);
    })
  },
  //选择预定时间
  pushToSelectAddress() {
    // wx.navigateTo({
    //   url: '/shopMallPackage/pages/addressList/addressList?isSelect=1',
    // })
    this.setData({
      showLiveTimePop: true,
    })
  },

  surePayAction() {
    if (!this.data.formData.bookingTime) {
      wx.showToast({
        title: '请选择预订时间',
        icon: "none"
      })
      return;
    }
    let arr = this.data.travelInfo;
    let isOk = true;
    arr.forEach((i) => {
      if (!i.name.trim() || !i.idCard.trim()) {
        isOk = false;
      }
    })
    if (!isOk) {
      wx.showToast({
        title: '请完成出行信息编写',
        icon: "none"
      })
      return;
    }
    if (!this.data.formData.contactName) {
      wx.showToast({
        title: '请输入联系人姓名',
        icon: "none"
      })
      return;
    }
    if (!this.data.formData.contactPhone) {
      wx.showToast({
        title: '请输入手机号',
        icon: "none"
      })
      return;
    }
    this.setData({
      // 'formData.bookingTime':this.data.formData.bookingTime + " " + "09:00:00",
      'formData.travelInfo': this.data.travelInfo
    })
    wx.showLoading({
      title: '支付中...',
    })
    console.log("JJLog:提交参数是:" + JSON.stringify(this.data.formData));
    activitySignUpRequest(this.data.formData).then(res => {
      console.log("JJLog:支付回调:" + JSON.stringify(res));
      if (res.code == 200) {
        if (this.data.payType == 1 || res.data.isFree) {
          wx.hideLoading();
          wx.navigateTo({
            url: '/storePackage/pages/exchangeSuccess/exchangeSuccess',
          })
          return;
        }
        console.log("JJLog:这里没来")
        let payData = res.data.data;
        wx.requestPayment({
          timeStamp: payData.timeStamp,
          nonceStr: payData.nonceStr,
          package: payData.packageValue,
          signType: 'MD5',
          paySign: payData.paySign,
          success: (res) => {
            wx.hideLoading();
            console.log("JJLog:微信支付成功回调:" + JSON.stringify(res));
            wx.showToast({
              title: '支付成功',
              icon: "success",
              duration: 2000
            })
            //回调成功调上面查询电话接口，进行电话拨打:
            setTimeout(() => {
              wx.navigateTo({
                url: '/storePackage/pages/exchangeSuccess/exchangeSuccess',
              })
            }, 2000);

          },
          fail: (err) => {
            wx.hideLoading();
            wx.showToast({
              title: '支付失败',
              icon: "none"
            })
            console.log("JJLog:微信支付失败回调:" + JSON.stringify(err));
          }
        });
      }
    }).catch(err => {
      console.error("JJLog报名参加活动失败:" + JSON.stringify(err));
      wx.hideLoading();
      wx.showToast({
        title: err || "操作失败",
        icon: "none"
      })
    })


  },

  // 新增出行人信息:
  addNewDutyAction() {
    let arr = this.data.travelInfo;
    let obj = {
      name: "",
      idCard: "",
    }
    arr.push(obj)
    this.setData({
      'travelInfo': arr
    })
    this.setData({
      showTextTitle: "确认支付x" + mathUtil.mul(this.data.activityDetail.integral, this.data.travelInfo.length) + "元"
    })
  },
  // 删除一个信息:
  cancelOneDuty(e) {
    let index = e.currentTarget.dataset.index;
    let arr = this.data.travelInfo;
    arr.splice(index, 1);
    this.setData({
      'travelInfo': arr
    })
    this.setData({
      showTextTitle: "确认支付x" + mathUtil.mul(this.data.activityDetail.integral, this.data.travelInfo.length) + "元"
    })
  },
  // 输入回调
  cellInputChange(e) {
    let key = e.currentTarget.dataset.key;
    let index = e.currentTarget.dataset.index
    let value = e.detail.value
    //动态数组:
    let changeItem = 'travelInfo[' + index + '].' + key;
    this.setData({
      [changeItem]: value,
    })
    //  console.log("JJLog:看看结果是:" + JSON.stringify(this.data.travelInfo));

  },
  contactInputBack(e) {
    let key = e.currentTarget.dataset.key;
    let value = e.detail.value
    //动态数组:
    let changeItem = `formData.${key}`
    this.setData({
      [changeItem]: value,
    })
  },
  timePopHidden() {
    this.setData({
      showLiveTimePop: false
    })
  },

  deliveryTimeSure(e) {
    console.log(e.detail.timeStr);
    this.setData({
      'formData.bookingTime': e.detail.timeStr + " " + "09:00:00",
    })
    this.timePopHidden();
  },

})